
#include <string.h>
#include <math.h>
#include <amanita/aMath.h>
#include <amanita/aString.h>
#include "TarotDeck.h"
#include "Card.h"


Card::Card(TarotDeck &d,int v,int s) : deck(&d),set(&d),state(s) {
	setValue(v);
	setLocation(0,0);
	setSize(0,0);
	name = 0;
	title = 0;
	image = 0;
}

Card::~Card() {
	if(name) { free(name);name = 0; }
	if(title) { free(title);title = 0; }
}

void Card::setName(const char *n) {
	if(name) free(name);
	name = strdup(n);
}

void Card::setTitle(const char *t) {
	if(title) free(title);
	title = strdup(t);
}

void Card::setValue(int v) {
	if(v<0) value = 0,number = 0,element = TAROT_AIR,sg1 = sg2 = 0,arcana = TAROT_MAJOR;
	else {
		value = v;
		sg1 = deck->cardSigns[v<<1],sg2 = deck->cardSigns[(v<<1)+1];
		if(v<22) number = v,element = deck->trumpElements[v],arcana = TAROT_MAJOR;
		else number = ((v-22)%14)+1,element = (tarot_element)((v-22)/14),arcana = number<=10? TAROT_MINOR : TAROT_COURT;
	}
	int i,e = (int)element;
	for(i=0; i<4; i++) eds[i] = 1;
	eds[e] = 5;
	if(isCourt()) eds[e]--,eds[app.occult.symbolElement(app.occult.charToSymbol(sg1))]++;
}

void Card::setImage(cairo_surface_t *i) {
	image = i;
	width = cairo_image_surface_get_width(i);
	height = cairo_image_surface_get_height(i);
}

cairo_surface_t *Card::getImage() {
	if(!image) return 0;
	return isBack()? deck->back : image;
}

void Card::setFlipped(bool f) {
	if((f && (state&CARD_FLIPPED)) || (!f && !(state&CARD_FLIPPED))) return;
	state = f? state|CARD_FLIPPED : state&~CARD_FLIPPED;
	flip();
}

void Card::flip() {
	int n;
	x += (height-width)/2;
	y += (width-height)/2;
	n = width,width = height,height = n;
}

void Card::makeOriginalState() {
	origin.set = set;
	origin.state = state;
	origin.x = x;
	origin.y = y;
	origin.width = width;
	origin.height = height;
}

void Card::returnToOriginalState() {
	set = origin.set;
	state = origin.state;
	x = origin.x;
	y = origin.y;
	width = origin.width;
	height = origin.height;
}

